// BoLe HR Platform - API调用工具

class APIClient {
    constructor() {
        this.baseURL = 'http://localhost:8000/api';
        this.token = localStorage.getItem('access_token');
        this.isDemoMode = this.checkDemoMode();
    }

    // 检查是否为演示模式
    checkDemoMode() {
        const currentUser = localStorage.getItem('currentUser');
        if (currentUser) {
            const userData = JSON.parse(currentUser);
            return userData.token && userData.token.includes('demo');
        }
        return false;
    }

    // 获取API端点（演示模式使用不同的路径）
    getEndpoint(path) {
        if (this.isDemoMode) {
            // 演示模式使用demo前缀
            if (path.startsWith('/hr/')) {
                return `/demo${path}`;
            } else if (path.startsWith('/candidate/')) {
                return `/demo${path}`;
            }
        }
        return path;
    }

    // 设置认证令牌
    setToken(token) {
        this.token = token;
        localStorage.setItem('access_token', token);
        this.isDemoMode = this.checkDemoMode(); // 重新检查演示模式
    }

    // 清除认证令牌
    clearToken() {
        this.token = null;
        localStorage.removeItem('access_token');
        localStorage.removeItem('user');
    }

    // 获取认证头
    getAuthHeaders() {
        const headers = {
            'Content-Type': 'application/json'
        };
        
        // 演示模式下不需要真实Token验证
        if (this.token && !this.isDemoMode) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }
        
        return headers;
    }

    // 处理API响应
    async handleResponse(response) {
        if (!response.ok) {
            const error = await response.json().catch(() => ({ detail: 'Request failed' }));
            throw new Error(error.detail || `HTTP ${response.status}`);
        }
        return response.json();
    }

    // 通用请求方法
    async request(endpoint, options = {}) {
        const actualEndpoint = this.getEndpoint(endpoint);
        const url = `${this.baseURL}${actualEndpoint}`;
        const config = {
            headers: this.getAuthHeaders(),
            ...options
        };

        try {
            const response = await fetch(url, config);
            return await this.handleResponse(response);
        } catch (error) {
            console.error('API Request failed:', error);
            throw error;
        }
    }

    // GET请求
    async get(endpoint) {
        return this.request(endpoint, { method: 'GET' });
    }

    // POST请求
    async post(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // PUT请求
    async put(endpoint, data) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    // DELETE请求
    async delete(endpoint) {
        return this.request(endpoint, { method: 'DELETE' });
    }

    // 文件上传
    async uploadFile(endpoint, formData) {
        const headers = {};
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }

        const response = await fetch(`${this.baseURL}${endpoint}`, {
            method: 'POST',
            headers,
            body: formData
        });

        return this.handleResponse(response);
    }

    // 认证相关API
    async register(userData) {
        return this.post('/auth/register', userData);
    }

    async login(credentials) {
        const response = await this.post('/auth/login', credentials);
        if (response.access_token) {
            this.setToken(response.access_token);
            localStorage.setItem('user', JSON.stringify(response.user));
        }
        return response;
    }

    async getCurrentUser() {
        return this.get('/auth/me');
    }

    async createCandidateProfile(profileData) {
        return this.post('/auth/candidate/profile', profileData);
    }

    async createHRProfile(profileData) {
        return this.post('/auth/hr/profile', profileData);
    }

    // HR相关API
    async getRecruitmentStats() {
        return this.get('/hr/dashboard/stats');
    }

    async createJob(jobData) {
        return this.post('/hr/jobs', jobData);
    }

    async getCompanyJobs(limit = 20, offset = 0) {
        return this.get(`/hr/jobs?limit=${limit}&offset=${offset}`);
    }

    async updateJob(jobId, jobData) {
        return this.put(`/hr/jobs/${jobId}`, jobData);
    }

    async searchCandidates(searchData) {
        return this.post('/hr/candidates/search', searchData);
    }

    async analyzeResume(resumeId, jobPositionId = null) {
        const endpoint = `/hr/resumes/${resumeId}/analyze`;
        const params = jobPositionId ? `?job_position_id=${jobPositionId}` : '';
        return this.post(endpoint + params, {});
    }

    async batchAnalyzeCandidates(batchData) {
        return this.post('/hr/candidates/batch-analyze', batchData);
    }

    async updateApplicationStatus(applicationId, statusData) {
        return this.put(`/hr/applications/${applicationId}/status`, statusData);
    }

    async verifyGitHub(githubData) {
        return this.post('/hr/github/verify', githubData);
    }

    async getHRRecommendations(recommendationData) {
        return this.post('/hr/recommendations', recommendationData);
    }

    async getJobApplications(jobId = null, status = null, limit = 20, offset = 0) {
        let params = new URLSearchParams();
        if (jobId) params.append('job_id', jobId);
        if (status) params.append('status', status);
        params.append('limit', limit);
        params.append('offset', offset);
        
        return this.get(`/hr/applications?${params.toString()}`);
    }

    async updateHRPreferences(preferences) {
        return this.post('/hr/preferences', preferences);
    }

    // 求职者相关API
    async getCandidateAnalytics() {
        return this.get('/candidate/dashboard/analytics');
    }

    async createOrUpdateProfile(profileData) {
        return this.post('/candidate/profile', profileData);
    }

    async searchJobs(searchData) {
        return this.post('/candidate/jobs/search', searchData);
    }

    async getJobMatches(matchData) {
        return this.post('/candidate/jobs/match', matchData);
    }

    async uploadResume(formData) {
        return this.uploadFile('/candidate/resumes/upload', formData);
    }

    async optimizeResume(resumeId, optimizationData) {
        return this.post(`/candidate/resumes/${resumeId}/optimize`, optimizationData);
    }

    async prepareForInterview(prepData) {
        return this.post('/candidate/interview/prepare', prepData);
    }

    async applyForJob(applicationData) {
        return this.post('/candidate/applications', applicationData);
    }

    async getMyApplications(status = null, limit = 20, offset = 0) {
        let params = new URLSearchParams();
        if (status) params.append('status', status);
        params.append('limit', limit);
        params.append('offset', offset);
        
        return this.get(`/candidate/applications?${params.toString()}`);
    }

    async getMyResumes() {
        return this.get('/candidate/resumes');
    }

    async getCandidateRecommendations(recommendationData) {
        return this.post('/candidate/recommendations', recommendationData);
    }
}

// 创建全局API客户端实例
const api = new APIClient();

// 工具函数
function showLoading(element) {
    if (element) {
        element.innerHTML = `
            <div class="loading">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载中...</span>
            </div>
        `;
    }
}

function showError(element, message) {
    if (element) {
        element.innerHTML = `
            <div class="error-state">
                <i class="fas fa-exclamation-triangle"></i>
                <h3>出错了</h3>
                <p>${message}</p>
            </div>
        `;
    }
}

function showEmpty(element, message) {
    if (element) {
        element.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <h3>暂无数据</h3>
                <p>${message}</p>
            </div>
        `;
    }
}

function showToast(message, type = 'info') {
    // 创建Toast通知
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <div class="toast-content">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;

    // 添加样式
    Object.assign(toast.style, {
        position: 'fixed',
        top: '100px',
        right: '20px',
        zIndex: '3000',
        padding: '1rem 1.5rem',
        borderRadius: '8px',
        color: 'white',
        fontWeight: '500',
        opacity: '0',
        transform: 'translateX(100%)',
        transition: 'all 0.3s ease'
    });

    // 设置背景色
    const colors = {
        success: '#28a745',
        error: '#dc3545',
        warning: '#ffc107',
        info: '#17a2b8'
    };
    toast.style.backgroundColor = colors[type] || colors.info;

    document.body.appendChild(toast);

    // 显示动画
    setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(0)';
    }, 100);

    // 自动隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
    }).format(amount);
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

function validateForm(formElement) {
    const inputs = formElement.querySelectorAll('input[required], select[required]');
    let isValid = true;

    inputs.forEach(input => {
        const value = input.value.trim();
        if (!value) {
            input.style.borderColor = 'var(--danger-color)';
            isValid = false;
        } else {
            input.style.borderColor = 'var(--border-color)';
        }

        // 特殊验证
        if (input.type === 'email' && value && !validateEmail(value)) {
            input.style.borderColor = 'var(--danger-color)';
            isValid = false;
        }
    });

    return isValid;
}